package com.blb.eduuserservice.config;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.blb.common.util.JwtUtils;
import com.blb.common.util.ResponseResult;
import com.blb.common.util.RsaUtils;
import com.blb.eduuserservice.service.IUserService;
import com.blb.eduuserservice.util.UserTokenUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.concurrent.TimeUnit;

/**
 * 登录成功处理器
 */
@Slf4j
@Component
public class LoginSuccessHandler implements AuthenticationSuccessHandler {

    @Autowired
    private RedisTemplate<String,String> redisTemplate;

    @Autowired
    private IUserService userService;

    //登录成功的回调
    @Override
    public void onAuthenticationSuccess(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Authentication authentication) throws IOException, ServletException {
        //获得用户名
        User user = (User) authentication.getPrincipal();
        //通过用户名查询用户信息
        com.blb.common.entity.User user1 = userService.getOne(new QueryWrapper<com.blb.common.entity.User>().lambda().eq(com.blb.common.entity.User::getUsername, user.getUsername()));
        ResponseResult<com.blb.common.entity.User> result = UserTokenUtils.generateUserToken(user1, redisTemplate);
        //发送token给前端
        ResponseResult.write(httpServletResponse, result);
    }
}
